import { Message } from "@arco-design/web-vue";

/* 生成随机数字 */
export const randomNumber = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

/* 生成随机颜色 */
export const randomColor = () => {
  return `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
};

export const copyText = (text: string) => {
  // 添加一个input元素放置需要的文本内容
  const copyContent = document.createElement("input");
  copyContent.value = text;
  document.body.appendChild(copyContent);
  // 选中并复制文本到剪切板
  copyContent.select();
  document.execCommand("copy");
  // 移除input元素
  document.body.removeChild(copyContent);
  Message.info("Success");
};

/**
 * element           要绑定事件的对象及HTML节点。
 * type              事件名称attachEvent监听的事件前边的加上“on”比如“onclick”和“onmouseover”addEventListener与之相反。
 * listener          要绑定的事件监听函数
 */
type eventType = "mousedown" | "mousemove" | "contextmenu" | string;
export const addEvent = function (element: any, type: eventType, callback: any) {
  if (element.addEventListener) {
    if (type.slice(0, 2) === "on") type = type.slice(2);
    element.addEventListener(type, callback);
  } else if (element.attachEvent) {
    if (type.slice(0, 2) !== "on") type = `on${type}`;
    element.attachEvent(type, callback);
  } else {
    type.slice(0, 2) !== "on" ? (element[`on${type}`] = callback) : (element[type] = callback);
  }
};
/**
 * @description 复制
 * @param {*} id DOM ID
 */
export const copyDomText = (node: HTMLElement) => {
  const createRange = document.createRange();
  createRange.selectNodeContents(node);
  const selection = document.getSelection() as Selection;
  selection.removeAllRanges();
  selection.addRange(createRange);
  document.execCommand("Copy");
  selection.removeAllRanges();
};

export const createStyle = (code: string) => {
  const style = document.createElement("style");
  // for Chrome Firefox Opera Safari
  style.appendChild(document.createTextNode(code));
  // for IE
  // style.styleSheet.cssText = code;
  const head = document.getElementsByTagName("head")[0]!;
  head.appendChild(style);
};
export const openLink = (href: string) => {
  const link = document.createElement("a") as HTMLAnchorElement;
  link.href = href;
  link.target = "_blank";
  document.body.append(link);
  link.click();
  setTimeout(() => link.parentNode?.removeChild(link));
};

// 删除事件

export function removeEvent(el: any, event: string, handler: Function) {
  if (!el) {
    return;
  }
  if (el.detachEvent) {
    el.detachEvent(`on${event}`, handler);
  } else if (el.removeEventListener) {
    el.removeEventListener(event, handler, true);
  } else {
    el[`on${event}`] = null;
  }
}

export const downloadText = (text: string, filename = "text") => {
  const element = document.createElement("a");
  element.setAttribute("href", `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`);
  element.setAttribute("download", filename);

  element.style.display = "none";
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
};
export const importAssets = (src: string) => {
  return importImage(`../assets/${src}`);
};
export const importImage = (src: string) => {
  return new URL(src, import.meta.url).href;
};

export function range(loc: number, min: number, max: number) {
  if (loc > max) {
    return max;
  }
  if (loc < min) {
    return min;
  }
  return loc;
}

/**
 * 描述:过滤布尔值
 *  */
export const filterBoolean = (bool: boolean, _true = "", _false = "") => {
  return bool ? _true : _false;
};

export const debounce = function (fn: Function, delay = 200) {
  // 实现防抖函数的核心是使用setTimeout
  // time变量用于保存setTimeout返回的Id

  let time: any = 0;

  function _debounce() {
    // 如果time不为0，也就是说有定时器存在，将该定时器清除
    if (time !== null) {
      clearTimeout(time);
    }

    time = setTimeout(() => {
      fn();
    }, delay);
  }

  // 防抖函数会返回另一个函数，该函数才是真正被调用的函数
  return _debounce;
};

/* 格式化时间 */
export const formatDate = (time?: Date) => {
  const date = !time ? new Date() : new Date(time);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const // 月份是从0开始的
    day = date.getDate();
  const hour = date.getHours();
  const min = date.getMinutes();
  const sec = date.getSeconds();
  const newTime = `${year}-${month}-${day} ${hour}:${min}:${sec}`;
  return newTime;
};

/**
 * 注释: 碰撞检测
 *
 * */
type position = { x: number; width: number; y: number; height: number };
export const collide = (rect1: position, rect2: position) => {
  let maxX;
  let maxY;
  let minX;
  let minY;

  maxX =
    rect1.x + rect1.width >= rect2.x + rect2.width ? rect1.x + rect1.width : rect2.x + rect2.width;
  maxY =
    rect1.y + rect1.height >= rect2.y + rect2.height
      ? rect1.y + rect1.height
      : rect2.y + rect2.height;
  minX = rect1.x <= rect2.x ? rect1.x : rect2.x;
  minY = rect1.y <= rect2.y ? rect1.y : rect2.y;

  if (maxX - minX <= rect1.width + rect2.width && maxY - minY <= rect1.height + rect2.height) {
    return true;
  }
  return false;
};

export function getAngle(x1: number, y1: number, x2: number, y2: number) {
  const dot = x1 * x2 + y1 * y2;
  const det = x1 * y2 - y1 * x2;
  const angle = (Math.atan2(det, dot) / Math.PI) * 180;
  return (angle + 360) % 360;
}

export function praseStrEmpty(str: string) {
  if (!str || str === "undefined" || str === "null") {
    return "";
  }
  return str;
}
export const getTimeZone = () => {
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
};
